package net.asfun.jvalog.service;

import java.util.ArrayList;
import java.util.List;

import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Label;
import net.asfun.jvalog.resource.LabelDao;
import net.asfun.jvalog.util.Bridge;
import net.asfun.jvalog.util.Unifier;
import net.asfun.jvalog.util.UpdateManager;
import net.asfun.jvalog.vo.Pager;
import net.asfun.jvalog.vo.Post;
import net.asfun.jvalog.vo.Tag;


import com.google.appengine.api.datastore.Key;

public class TagService {
	
	public static List<Tag> listAll() {
		List<Tag> tags = new ArrayList<Tag>();
		for (Label label : LabelDao.listAll()) {
			tags.add(new Tag(label));
		}
		return tags;
	}

	public static Tag getBySlogan(String slogan) {
		return new Tag(LabelDao.getBySlogan(slogan));
	}

	public static List<Post> listPublished(Tag tag, Pager pager) {
		return tag.listPublishedPosts(pager);
	}

	public static void delete(Long id) {
		Label label = JdoerFactory.jdoLabel.load(id);
		if ( label != null ) {
			Unifier.unsetUnique(label.getKey(), "slogan");
			JdoerFactory.jdoRelation.delete(Bridge.getRelationsByRight(label.getKey(), Bridge.POST_TAG));
			JdoerFactory.jdoLabel.delete(label);
			UpdateManager.enableCacheTask();
		}
	}

	public static void update(Long id, String name, String slogan) {
		Label label = JdoerFactory.jdoLabel.load(id);
		label.setName(name);
		label.setSlogan(uniqueURI(slogan, label.getKey()));

		Unifier.setUnique(label.getKey(), "slogan", label.getSlogan());
		UpdateManager.enableCacheTask();
	}
	
	private static String uniqueURI(String slogan, Key key) {
		if ( ! Unifier.isUnique(key, "slogan", slogan)) {
			slogan += "~1";
			return slogan = uniqueURI(slogan, key);
		}
		return slogan;	
	}

	public static Object getById(Long id) {
		return new Tag(JdoerFactory.jdoLabel.load(id));
	}
}
